<template>
  <div class="flow-setting">
    <div class="flow-setting-header">
      <div class="header-left">
        <div class="header-left-back" @click="toReturn">
          <i class="iconfont iconfont-left">&#xe601;</i>
        </div>
        <div class="header-left-title">{{ workFlowDef.name }}</div>
      </div>
      <div class="header-center">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="① 基本信息" :name="1"></el-tab-pane>
          <el-tab-pane label="② 流程设计" :name="2"></el-tab-pane>
        </el-tabs>
      </div>
      <div class="header-right">
        <el-button @click="saveSet">发布</el-button>
      </div>
    </div>
    <div class="flow-setting-content">
      <!-- 基础设置 -->
      <div v-show="activeTab === 1" class="base-setting">
        <el-form ref="workFlowDefRef" :model="workFlowDef" label-position="top" label-width="80px" :rules="workFlowDefRules">
          <el-form-item label="流程名称" prop="name">
            <el-input v-model="workFlowDef.name" placeholder="请输入流程名称"></el-input>
          </el-form-item>
          <el-form-item label="所在分组" prop="groupId">
            <el-select v-model="workFlowDef.groupId" placeholder="请选择分组" style="width: 100%;">
              <el-option v-for="item in groupList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="流程管理员" prop="admins">
            <el-select v-model="workFlowDef.admins" placeholder="请选择流程管理员" multiple style="width: 100%;">
              <el-option v-for="item in store.state.flow.operatorData.user" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="流程说明">
            <el-input placeholder="请输入流程说明" v-model="workFlowDef.remark" type="textarea" show-word-limit :autosize="{ minRows: 3, maxRows: 5}" maxlength="500"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <!-- 流程设计 -->
      <NodeSetting v-show="activeTab === 2" v-model:nodeConfig="nodeConfig" v-model:tipVisible="tipVisible" :tipList="tipList" />
    </div>
    <errorDialog v-model:visible="tipVisible" :list="tipList" />
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { createBpmn, getFlowDetail, getFlowGroupList, checkName } from '@/api/workflow'
import { placeholderList } from '@/utils/flowConst'
import { useStore } from 'vuex'

let store = useStore()
const router = useRouter()

const activeTab = ref(1)
const groupList = ref([])
const _getFlowGroupList = async () => {
  const res = await getFlowGroupList()
  if(res.code === 20000){
    groupList.value = res.data
  }
}
_getFlowGroupList()

// 流程信息
const editId = ref(null)
const workFlowDef = ref({})
let nodeConfig = ref({ // 默认包含发起人节点
  "id": "root",
  "pid": "",
  "nodeName": "发起人",
  "type": 'start',
  "initiatorType": "everyone",
  "users": [],
  "departs": [],
  "roles": [],
  "childNode": {
    "id": "end",
    "nodeName": "流程结束",
    "type": "end"
  }
})

// 流程详情获取
const _getFlowDetail = async (id) => {
  const res = await getFlowDetail({ id })
  if(res.code === 20000) {
    const detail = JSON.parse(res.data.json)
    workFlowDef.value = detail.workFlowDef
    workFlowDef.value.groupId = res.data.groupId
    nodeConfig.value = detail.nodeConfig
    editId.value = res.data.id
  }
}

// 流程保存（发布和更新）
const saveSet = async () => {
  store.commit('flow/setIsTried', true)
  tipList.value = []
  formValid()
  if(!nodeConfig.value.childNode.childNode){
    tipList.value.push({ stepName: '流程设计', description: '流程至少添加一个节点' })
  }
  nodeValid(nodeConfig.value)
  if (tipList.value.length != 0) {
    tipVisible.value = true
    return
  }
  const data = {
    id: editId.value,
    code: 'xxxx12',
    autoDeploy: true,
    nodeConfig: nodeConfig.value,
    workFlowDef: workFlowDef.value
  }
  let res = await createBpmn(data)
  if (res.code == 20000) {
    window.opener.updateFlow('发布成功')
    window.close()
  }
}

// 表单校验
const workFlowDefRef = ref(null)
const workFlowDefRules = reactive({
  name: [{ required: true, message: '流程名称不能为空', trigger: 'blur' }],
  groupId: [{required: true, message: '请选择流程分组', trigger: 'change'}],
  admins: [{required: true, message: '请选择流程管理员', trigger: 'blur'}]
})
const formValid = async () => {
  if(!workFlowDef.value.name){
    tipList.value.push({
      stepName: '基本信息',
      description: '流程名称未填写',
    })
  }else{
    const res = await checkName({ name: workFlowDef.value.name, groupId: workFlowDef.value.groupId })
    if(res.code === 20000 && res.data) {
      tipList.value.push({
        stepName: '基本信息',
        description: '流程名称在该分组下已存在',
      })
    }
  }
  if(!workFlowDef.value.groupId){
    tipList.value.push({
      stepName: '基本信息',
      description: '流程分组未选择',
    })
  }
  if(workFlowDef.value.admins.length === 0){
    tipList.value.push({
      stepName: '基本信息',
      description: '流程管理员未设置',
    })
  }
}

// 流程设计校验
const tipList = ref([])
const tipVisible = ref(false)
const nodeValid = ({ childNode }) => {
  if (childNode) {
    let { type, error, nodeName, conditionNodes } = childNode
    if (type == 'approval' || type == 'cc') {
      if (error) {
        const description = `${nodeName}未选择${placeholderList[type]}`
        tipList.value.push({
          stepName: '流程设计',
          description
        })
      }
      nodeValid(childNode)
    } else if (type == 'condition') {
      nodeValid(childNode)
    } else if (type == 'exclusive') {
      nodeValid(childNode)
      for (var i = 0; i < conditionNodes.length; i++) {
        if (conditionNodes[i].error) {
          const description = `${conditionNodes[i].nodeName}未选择条件`
          tipList.value.push({ stepName: '流程设计', description })
        }
        nodeValid(conditionNodes[i])
      }
    }
  } else {
    childNode = null
  }
}

// 返回
const toReturn = () => {
  window.close()
}

onMounted(async () => {
  const {id, groupId} = router.currentRoute.value.query
  if(id) {
    _getFlowDetail(id)
  }
  if(groupId){
    workFlowDef.value.groupId = Number(groupId)
  }
})
</script>

<style lang="scss" scoped>
.flow-setting{
  .flow-setting-header{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 60px;
    background: $mainColor;
    .header-left{
      flex: 1;
      display: flex;
      align-items: center;
      color: #fff;
      .header-left-back{
        width: 60px;
        height: 60px;
        border-right: 1px solid #aaa;
        line-height: 60px;
        cursor: pointer;
        text-align: center;
        &:hover{
          opacity: 0.8;
        }
        i{
          display: inline-block;
          font-size: 24px;
          font-weight: 600;
          transform: rotate(90deg);
        }
      }
      .header-left-title{
        font-size: 16px;
        margin-left: 10px;
      }
    }
    .header-center{
      flex: 2;
      display: flex;
      justify-content: center;
      ::v-deep(.el-tabs__item){
        color: $white;
      }
      ::v-deep(.el-tabs__item.is-active){
        color: $white;
      }
      ::v-deep(.el-tabs__nav-wrap::after){
        background: transparent;
      }
      ::v-deep(.el-tabs__active-bar){
        background: $white;
      }
      ::v-deep(.el-tabs__header){
        margin: 0;
      }
    }
    .header-right{
      flex: 1;
      display: flex;
      justify-content: flex-end;
      padding-right: 16px;
    }
  }
  .flow-setting-content{
    height: calc(100vh - 60px);
    overflow: auto;
    background: #f5f5f7;
    .base-setting {
      overflow: auto;
      margin: 0 auto;
      width: 600px;
      background: #ffffff;
      margin-top: 10px;
      padding: 15px 20px;
      ::v-deep .el-form-item__label {
        padding: 0;
        margin-bottom: 0 !important;
        font-weight: bold;
      }
    
      ::v-deep .el-form-item {
        margin-bottom: 15px;
      }
    }
  }
}

.error-modal-list {
  width: 455px;
}
</style>